package com.dongge.service;

import com.dongge.dao.CURDDaoBase;
import com.dongge.entity.Article;
import com.dongge.entity.Comment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * Created by Administrator on 2015/10/17.
 */
@Service
public class CommentService extends CURDDaoBase<Comment>{

    @Resource
    private ArticleService articleService;

    /**
     * 获取文章的评论列表(一级评论）
     * @param articleId
     * @return
     */
    public List<Comment> getArticleTopComments(Long articleId){
        if(articleId == null)
            return Collections.emptyList();
        String hsql =
                "from Comment p where p.article = :articleId and p.parent is null";
        return getSession().createQuery(hsql)
                .setLong("articleId",articleId)
                .list();
    }

    /**
     * 获取评论页
     * @param articleId
     * @param targetPage
     * @param sizePage
     * @return
     */
    public Page getPage(Long articleId,int targetPage,int sizePage){
        if(targetPage < 1){
            targetPage = 1;
        }
        String hsql = "from Article";
        String chsql = "select count(*) from Comment where ";
        //count(*)返回的数据是long类型
        int count = ((Number)getSession().createQuery(chsql).uniqueResult()).intValue();
        List<Article> articles =  getSession().createQuery(hsql)
                .setFirstResult((targetPage-1)*sizePage)
                .setMaxResults(sizePage)
                .list();
        return  new Page(articles,targetPage,sizePage,count);
    }
}
